package com.yitongmao.fragment;


import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yitongmao.AppConstancts;
import com.yitongmao.activity.PlaceOrderActivity;
import com.yitongmao.adapter.ShoppingAdapter;
import com.yitongmao.bean.CloseAnAccountBean;
import com.yitongmao.bean.LoginHuancunBean;
import com.yitongmao.bean.ShoppingBean;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.dialog.CommomDialog;
import com.yitongmao.util.SignUtil;
import com.yitongmao.util.ToastUtils;
import com.yitongmao.yitmfruit.R;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;

public class ShoppingFragment extends Fragment implements View.OnClickListener
        , ShoppingAdapter.CheckInterface, ShoppingAdapter.ModifyCountInterface {
    private static final String TAG = "ShoppingCartActivity";
    @Bind(R.id.rl_bottom)
    AutoLinearLayout rlBottom;
    @Bind(R.id.mNull)
    ImageView mNull;
    @Bind(R.id.dataNull)
    TextView dataNull;
    //标题 购物车
    private TextView tvTitle;
    //编辑 完成
    private TextView tvEdit;
    //全选
    CheckBox ckAll;
    //不含运费
    private TextView notExpressCharges;
    //总额
    TextView tvShowPrice;
    //结算
    TextView tvSettlement;
    //水果列表
    private ListView lvFruit;
    //总数量
    private int totalCount;
    //总价
    private double totalPrice;
    //编辑还是删除
    private boolean flag;
    private LoginHuancunBean loginHuancunBean;
    private ShoppingAdapter shoppingAdapter;
    private List<ShoppingBean.GoodsListBean> goodsList;
    private String userId;
    private TextView tv_edit_right;
    private int loginId1;
    private CloseAnAccountBean closeAnAccountBean;
    private Dialog bottomDialog;
    private boolean isComing = true;
    private String name;
    private AutoRelativeLayout yushouyx;
    private AutoRelativeLayout xianhuoyx;

    public ShoppingFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shopping, container, false);
        ButterKnife.bind(this, view);
        initView(view);
        return view;
    }

    private void initView(View view) {
        //编辑
        tv_edit_right = (TextView) view.findViewById(R.id.tv_edit_right);
        //顶部
        //btnBack = (ImageView) view.findViewById(R.id.btn_back);
        tvTitle = (TextView) view.findViewById(R.id.tv_title);
        tvEdit = (TextView) view.findViewById(R.id.tv_edit_right);
        lvFruit = (ListView) view.findViewById(R.id.fruit_lv);
        ckAll = (CheckBox) view.findViewById(R.id.ck_all);
        tvShowPrice = (TextView) view.findViewById(R.id.tv_show_price);
        notExpressCharges = (TextView) view.findViewById(R.id.not_express_charges);
        tvSettlement = (TextView) view.findViewById(R.id.tv_settlement);
       // btnBack.setOnClickListener(this);
        tvEdit.setOnClickListener(this);
        ckAll.setOnClickListener(this);
        tvSettlement.setOnClickListener(this);
        //解析查找的缓存并判断
        Gson gson = new Gson();
        String loginId = ACache.get(getActivity()).getAsString("loginId");
        if (loginId != null) {
            loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
            int id = loginHuancunBean.userInfo.id;
            loginId1 = loginHuancunBean.userInfo.loginId;
            userId = String.valueOf(id);
            shoppingListNetWork(userId);
        } else {
            tv_edit_right.setVisibility(View.GONE);
            lvFruit.setVisibility(View.GONE);
            rlBottom.setVisibility(View.GONE);
            mNull.setVisibility(View.VISIBLE);
        }
    }

    public void shoppingListNetWork(String userId) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId", userId);
        params.put("timestamp", timestamp);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("nonce", nonce);
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.shoppingListUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                String string = (String) result;
                Gson gson = new Gson();
                ShoppingBean shoppingBean = gson.fromJson(string, ShoppingBean.class);
                goodsList = shoppingBean.goodsList;
                Log.e("zzz", result.toString());
                if (shoppingBean.result.state.equals("1")) {
                    ACache.get(getActivity()).put("shoppingList", string, 30 * 24 * 60 * 60 * 60);
                }
                if (goodsList != null) {
                    shoppingAdapter = new ShoppingAdapter(getActivity(), goodsList);
                    shoppingAdapter.setCheckInterface(ShoppingFragment.this);
                    shoppingAdapter.setModifyCountInterface(ShoppingFragment.this);
                    shoppingAdapter.setShoppingCartBeanList(goodsList);
                    //是否全选
                    if (isAllCheck()) {
                        ckAll.setChecked(true);
                    } else {
                        ckAll.setChecked(false);
                    }
                    lvFruit.setAdapter(shoppingAdapter);
                    tvTitle.setText(goodsList.size() == 0 ? "购物车" : "购物车(" + goodsList.size() + ")");
                } else {
                    lvFruit.setVisibility(View.GONE);
                    mNull.setVisibility(View.VISIBLE);
                    rlBottom.setVisibility(View.GONE);
                    tv_edit_right.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.btn_back:
                break;
            //编辑 完成
            case R.id.tv_edit_right:
                flag = !flag;
                if (flag) {//在删除界面
                    tvEdit.setText("完成");
                    tvSettlement.setText("删除");
                    tvSettlement.setBackgroundColor(Color.parseColor("#FF3333"));
                    shoppingAdapter.isShow(false);
                    for (int i = 0; i < goodsList.size(); i++) {
                        goodsList.get(i).setDelCheck(false);
                    }
                    ckAll.setChecked(false);
                    shoppingAdapter.notifyDataSetChanged();
                } else {//在结算界面
                    tvEdit.setText("编辑");
                    tvSettlement.setBackgroundColor(Color.parseColor("#f5b410"));
                    shoppingAdapter.isShow(true);
                    if (isAllCheck()) {
                        ckAll.setChecked(true);
                    } else {
                        ckAll.setChecked(false);
                    }
                    statistics();
                    shoppingAdapter.notifyDataSetChanged();
                }
                break;
            //全选 · 全不选
            case R.id.ck_all:
                if (!flag) {
                    if (goodsList.size() != 0) {
                        if (ckAll.isChecked()) {
                            for (int i = 0; i < goodsList.size(); i++) {
                                goodsList.get(i).setCheck(true);
                            }
                            shoppingAdapter.notifyDataSetChanged();
                        } else {
                            for (int i = 0; i < goodsList.size(); i++) {
                                goodsList.get(i).setCheck(false);
                            }
                            shoppingAdapter.notifyDataSetChanged();
                        }
                    }
                    statistics();
                } else {
                    if (goodsList.size() != 0) {
                        if (ckAll.isChecked()) {
                            for (int i = 0; i < goodsList.size(); i++) {
                                goodsList.get(i).setDelCheck(true);
                            }
                            shoppingAdapter.notifyDataSetChanged();
                        } else {
                            for (int i = 0; i < goodsList.size(); i++) {
                                goodsList.get(i).setDelCheck(false);
                            }
                            shoppingAdapter.notifyDataSetChanged();
                        }
                    }
                }
                break;
            //结算 · 删除
            case R.id.tv_settlement:
                if (flag) {
                   /* for (int i = goodsList.size() - 1; i >= 0; i--) {
                        if (!goodsList.get(i).isDelCheck()) {
                            ToastUtils.showShort(getActivity(), "请选中后再删除");
                        } else {*/
                    new CommomDialog(getActivity(), R.style.dialog, "您确定删除此信息？", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            final StringBuffer stringBuffer = new StringBuffer();
                            for (int i = goodsList.size() - 1; i >= 0; i--) {
                                if (goodsList.get(i).isDelCheck()) {
                                    stringBuffer.append(goodsList.get(i).id).append(",");
                                    goodsList.remove(i);
                                }
                            }
                            String s = null;//删除
                            s = stringBuffer.toString().substring(0, (stringBuffer.toString().length() - 1));
                            if (!TextUtils.isEmpty(s)) {
                                setNetWork(userId, s);
                                tvTitle.setText(goodsList.size() == 0 ? "购物车" : "购物车(" + goodsList.size() + ")");
                                shoppingAdapter.notifyDataSetChanged();
                            }
                        }
                    }).setTitle("确定删除此商品吗？").show();
              /*          }
                    }*/
                } else {//结算
                    goToPay();
                }
        }
    }

    public void shoppingCloseAnAccount(String userId, String ids) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId", userId);
        params.put("ids", ids);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.shoppingCloseAnAccount, params, new CallBackListener() {
            @Override
            public void onStart() {
            }
            @Override
            public void onSuccess(Object result) {
                Log.e("onSuccess", result.toString());
                String string = (String) result;
                Gson gson = new Gson();
                closeAnAccountBean = gson.fromJson(string, CloseAnAccountBean.class);
                ToastUtils.showShort(getActivity(),closeAnAccountBean.result.message);
                if (closeAnAccountBean.sportSize > 0 || closeAnAccountBean.advanceSize > 0) {
                    diaLog(); //现货
                }
            }
            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }

    private void diaLog() {
        bottomDialog = new Dialog(getActivity(), R.style.BottomDialog);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.alert_dialog2, null);
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
        //点击屏幕外边消失dialog
        contentView.findViewById(R.id.lala).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
        yushouyx = (AutoRelativeLayout) contentView.findViewById(R.id.yushouyx);
        xianhuoyx = (AutoRelativeLayout) contentView.findViewById(R.id.xianhuoyx);

        TextView mYuShouNum = (TextView) contentView.findViewById(R.id.mYuShouNum);
        TextView mYuShouPrice = (TextView) contentView.findViewById(R.id.mYuShouPrice);
        Button mYuShouJieSuan = (Button) contentView.findViewById(R.id.mYuShouJieSuan);
        Button mXianHuoJieSuan = (Button) contentView.findViewById(R.id.mXianHuoJieSuan);
        TextView mXianHuoNum = (TextView) contentView.findViewById(R.id.mXianHuoNum);
        TextView mXianHuoPrice = (TextView) contentView.findViewById(R.id.mXianHuoPrice);
        int advanceSize = closeAnAccountBean.advanceSize;
        if (advanceSize > 0) {
            //yushouyx.setVisibility(View.VISIBLE);
            mYuShouNum.setText("共" + advanceSize + "件,需付：");
        }
        double advancePrice = closeAnAccountBean.advancePrice;
        if (advancePrice > 0) {
            mYuShouPrice.setText("￥" + advancePrice + "万");
        }
        int sportSize = closeAnAccountBean.sportSize;
        if (sportSize > 0) {
            //xianhuoyx.setVisibility(View.GONE);
            mXianHuoNum.setText("共" + sportSize + "件,需付：");
        }
        double sportPrice = closeAnAccountBean.sportPrice;
        if (sportPrice > 0) {
            mXianHuoPrice.setText("￥" + sportPrice + "万");
        }
        mYuShouJieSuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (closeAnAccountBean.advanceList.size()<=0){
                    ToastUtils.showShort(getActivity(),"选择商品");
                }else {
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append(closeAnAccountBean.advanceList).append(",");
                    String substring = stringBuffer.toString().substring(1, (stringBuffer.toString().length() - 2));
                    intoCloseAnAccount(userId, substring, closeAnAccountBean.advanceType);
                }
            }
        });
        mXianHuoJieSuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (closeAnAccountBean.sportList.size()<=0){
                    ToastUtils.showShort(getActivity(),"选择商品");
                }else {
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append(closeAnAccountBean.sportList).append(",");
                    String substring = stringBuffer.toString().substring(1, (stringBuffer.toString().length() - 4));
                    intoCloseAnAccount2(userId, substring, closeAnAccountBean.sportType);
                }
            }
        });
    }
    //进入结算页
    public void intoCloseAnAccount(String userId, final String ids, final String goodsType) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId", userId);
        params.put("ids", ids);
        params.put("goodsType", goodsType);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.intoCloseAnAccount, params, new CallBackListener() {
            @Override
            public void onStart() {
            }
            @Override
            public void onSuccess(Object result) {
                Log.e("zzz", result.toString());
                String string = (String) result;
                ACache.get(getActivity()).put("submitIndent", string, 30 * 24 * 60 * 60 * 60);
                Intent intent = new Intent(getActivity(), PlaceOrderActivity.class);
                intent.putExtra("ids", ids);
                intent.putExtra("advanceType", goodsType);
                startActivity(intent);
            }
            @Override
            public void onFail(Object result) {
                Log.e("zzz", result.toString());
                ToastUtils.showShort(getActivity(), "失败");
            }
        });
    }
    //进入结算页
    public void intoCloseAnAccount2(String userId, final String ids, final String goodsType) {
        final String replaceid = ids.replace(".0", "");
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId", userId);
        params.put("ids", replaceid);
        params.put("goodsType", goodsType);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.intoCloseAnAccount, params, new CallBackListener() {
            @Override
            public void onStart() {}
            @Override
            public void onSuccess(Object result) {
                String string = (String) result;
                ACache.get(getActivity()).put("submitIndent", string, 30 * 24 * 60 * 60 * 60);
                Intent intent = new Intent(getActivity(), PlaceOrderActivity.class);
                intent.putExtra("ids", replaceid);
                intent.putExtra("advanceType", goodsType);
                startActivity(intent);
            }
            @Override
            public void onFail(Object result) {
                Log.e("zzz", result.toString());
                ToastUtils.showShort(getActivity(), "失败");
            }
        });
    }
    private void goToPay() {
        StringBuffer stringBuffer = new StringBuffer();
        //选中的需要提交的商品清单
        for (int i = 0; i < goodsList.size(); i++) {
            boolean choosed = goodsList.get(i).isCheck();
            Log.e("zzz", choosed + "");
            if (choosed) {
                stringBuffer.append(goodsList.get(i).id).append(",");
                String s = null;//删除
                s = stringBuffer.toString().substring(0, (stringBuffer.toString().length() - 1));
                shoppingCloseAnAccount(userId, s);
                //计算所有价格并且封装成一个对象传给支付界面
            }

        }
    }
    @Override
    public void onPause() {
        super.onPause();
        isComing = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isComing) return;
        try {
            bottomDialog.dismiss();
            shoppingListNetWork(userId);
        } catch (Exception e) {
            Log.e("zzz", "" + e);
        }
    }
    /**
     * 单选
     */
    @Override
    public void checkGroup(int position, boolean isChecked) {
        if (!flag) {
            goodsList.get(position).setCheck(isChecked);
            if (isAllCheck()) {
                ckAll.setChecked(true);
            } else {
                ckAll.setChecked(false);
            }
            shoppingAdapter.notifyDataSetChanged();
        } else {
            goodsList.get(position).setDelCheck(isChecked);
            if (isDelAllCheck()) {
                ckAll.setChecked(true);
            } else {
                ckAll.setChecked(false);
            }
        }
        statistics();
    }

    /**
     * 统计操作
     * 1.先清空全局计数器
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        totalCount = 0;
        totalPrice = 0.00;
        if (flag) {
            for (int i = 0; i < goodsList.size(); i++) {
                ShoppingBean.GoodsListBean goodsBean = goodsList.get(i);
                if (goodsBean.isDelCheck()) {
                    totalCount++;
                    totalPrice += goodsBean.getTradePrice() * goodsBean.getNum();
                }
            }
            tvSettlement.setText("删除(" + totalCount + ")");
        } else {
            for (int i = 0; i < goodsList.size(); i++) {
                ShoppingBean.GoodsListBean goodsBean = goodsList.get(i);
                if (goodsBean.isCheck()) {
                    totalCount++;
                    totalPrice += goodsBean.getTradePrice() * goodsBean.getNum();
                }
            }
            tvSettlement.setText("结算(" + totalCount + ")");
        }
        tvShowPrice.setText("" + totalPrice);
        if (goodsList.size() == 0) {
            tv_edit_right.setVisibility(View.GONE);
            rlBottom.setVisibility(View.GONE);
            dataNull.setVisibility(View.VISIBLE);
        } else {
            tv_edit_right.setVisibility(View.VISIBLE);
            rlBottom.setVisibility(View.VISIBLE);
            dataNull.setVisibility(View.GONE);
        }

    }

    //增加数量
    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked) {
        ShoppingBean.GoodsListBean shoppingCartBean = goodsList.get(position);
        int currentCount = shoppingCartBean.getNum();
        if (currentCount == 99)
            return;
        currentCount++;
        shoppingCartBean.setNum(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        shoppingAdapter.notifyDataSetChanged();
        statistics();
    }

    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {
        ShoppingBean.GoodsListBean shoppingCartBean = goodsList.get(position);
        int currentCount = shoppingCartBean.getNum();
        if (currentCount == 1) {
            return;
        }
        currentCount--;
        shoppingCartBean.setNum(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        shoppingAdapter.notifyDataSetChanged();
        statistics();
    }

    @Override
    public void childDelete(int position) {
    }

    /**
     * 修改商品规格
     *
     * @param position
     */
    @Override
    public void doUpdateSpecifications(int position) {
        // showUpdateDialog(position);
    }

    /**
     * 遍历是否选中购买 list集合
     *
     * @return
     */
    private boolean isAllCheck() {
        for (ShoppingBean.GoodsListBean goodsBean : goodsList) {
            if (!goodsBean.isCheck())
                return false;
        }
        return true;
    }

    /**
     * 遍历是否选中删除 list集合
     *
     * @return
     */
    public boolean isDelAllCheck() {
        for (ShoppingBean.GoodsListBean goodsBean : goodsList) {
            if (!goodsBean.isDelCheck())
                return false;
        }
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    //删除购物车商品
    public void setNetWork(String userId, String ids) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId", userId);
        params.put("ids", ids);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.deleteShoppingUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                Log.e("onSuccess", result.toString());
            }

            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }
}
